<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="4" :xs="24" class="tree-side" >
        <div class="head-container">
          <el-input
            v-model="jxDeptTree.jxDeptName"
            placeholder="请输入部门名称"
            clearable
            size="small"
            prefix-icon="el-icon-search"
            style="margin-bottom: 20px"
          />
        </div>
        <div class="head-container">
          <el-tree
            :data="jxDeptTree.options"
            node-key="id"
            :props='{children:"children", label:"name"}'
            :expand-on-click-node="false"
            :highlight-current="true"
            :filter-node-method="filterNode"
            ref="tree"
            default-expand-all
            @node-click="handleNodeClick"
          />
        </div>
      </el-col>
      <el-col :span="20" :xs="24" class="table-side">
        <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
          <el-form-item label="学生工号" prop="studentCod">
            <el-input
              v-model="queryParams.studentCod"
              placeholder="请输入学生工号"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="学生姓名" prop="name">
            <el-input
              v-model="queryParams.name"
              placeholder="请输入学生姓名"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              icon="el-icon-plus"
              size="mini"
              :disabled="!queryParams.jxDeptId||queryParams.jxDeptType!='1'"
              @click="handleAdd"
              v-hasPermi="['jx:jxstudent:add']"
            >新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="success"
              icon="el-icon-edit"
              size="mini"
              :disabled="single"
              @click="handleUpdate"
              v-hasPermi="['jx:jxstudent:edit']"
            >修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              :disabled="multiple"
              @click="handleDelete"
              v-hasPermi="['jx:jxstudent:remove']"
            >删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="warning"
              icon="el-icon-download"
              size="mini"
              @click="handleExport"
              v-hasPermi="['jx:jxstudent:export']"
            >导出</el-button>
          </el-col>
        </el-row>

        <el-table v-loading="loading" :data="jxstudentList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="学生工号" align="center" prop="studentCod" />
          <el-table-column label="学生姓名" align="center" prop="name" />
          <el-table-column label="班级id" align="center" prop="jxDeptId" />
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleArchives(scope.row)"
              >查看档案</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['jx:jxstudent:edit']"
              >修改</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['jx:jxstudent:remove']"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />

        <!-- 添加或修改家校学生对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
          <el-form ref="form" :model="form" :rules="rules" label-width="80px">
            <el-form-item label="学生姓名" prop="name">
              <el-input v-model="form.name" placeholder="请输入学生姓名" />
            </el-form-item>
            <el-form-item label="家长" prop="nssJxParents">
              <div class="parent-item" :class="item.valid=='0'?'invalid':''" v-if="item.isActive=='1'" v-for="(item, index) in form.nssJxParents">
                <el-select v-model="item.relation" placeholder="关系">
                  <el-option
                    v-for="dict in relationOptions"
                    :key="dict.dictValue"
                    :label="dict.dictLabel"
                    :value="dict.dictValue"
                  ></el-option>
                </el-select>
                <el-input v-model="item.mobile" placeholder="请填写家长手机号" />
                <el-button type="text" icon="el-icon-close" circle @click="delParent(item,index)"></el-button>
                <div class="valid-error">{{item.error}}</div>
              </div>
              <el-button @click="addParent" type="text">添加家长</el-button>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="submitForm">确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
          </div>
        </el-dialog>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { listJxstudent, getJxstudent, delJxstudent, addJxstudent, updateJxstudent, exportJxstudent } from "@/api/jx/jxstudent";
import { listJxdept } from "@/api/jx/jxdept";
import {Message} from "element-ui";
export default {
  name: "Jxstudent",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 家校学生表格数据
      jxstudentList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      relationOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        isActive: undefined,
        wxStudentId: undefined,
        studentCod: undefined,
        name: undefined,
        jxDeptId: undefined,
        jxDeptType: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: '请输入活动名称', trigger: 'blur' }
        ]
      },
      jxDeptTree:{
        jxDeptName:"",
        options:[]
      }
    };
  },
  created() {
    this.getJxDeptTree();
    this.getList();
    this.getDicts("SYS_QYWX_STUDENT_RELATION").then(response => {
      this.relationOptions = response.data;
    });
  },
  methods: {
    /** 查询家校学生列表 */
    getList() {
      this.loading = true;
      listJxstudent(this.queryParams).then(response => {
        this.jxstudentList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset(jxDeptId) {
      this.form = {
        id: undefined,
        createBy: undefined,
        createTime: undefined,
        updateTime: undefined,
        updateBy: undefined,
        isActive: "1",
        lesseeId: undefined,
        wxStudentId: undefined,
        studentCod: undefined,
        name: undefined,
        jxDeptId: jxDeptId||undefined,
        toWxTime: undefined,
        nssJxParents: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!=1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      let curNode = this.$refs.tree.getCurrentNode();
      if(!curNode || !curNode.id){
        Message({
          message: "请先选择家校部门",
          type: 'error'
        })
        return;
      }
      this.reset(curNode.id);
      this.open = true;
      this.title = "添加家校学生";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getJxstudent(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改家校学生";
      });
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if(!this.jxParentsValid()){
            return
          }
          if (this.form.id != undefined) {
            updateJxstudent(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              }
            });
          } else {
            addJxstudent(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }
            });
          }
        }else{
          this.jxParentsValid()
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除家校学生编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delJxstudent(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function() {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有家校学生数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportJxstudent(queryParams);
        }).then(response => {
          this.download(response.msg);
        }).catch(function() {});
    },

    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.jxDeptId = data.id
      this.queryParams.jxDeptType = data.type
      this.getList();
    },
    getJxDeptTree(){
      listJxdept().then(response => {
        this.jxDeptTree.options = [];
        const data = { id: 1, name: '顶级节点', children: [] };
        data.children = this.handleTree(response.data, "wxDeptId", "wxParentId","children","1");
        this.jxDeptTree.options.push(data);
      });
    },
    addParent(){
      if(!this.form.nssJxParents){
        this.form.nssJxParents = []
      }
      this.form.nssJxParents.push({relation:'',mobile:'',isActive:'1'})
    },
    delParent(item,index){
      if(item.id){
        item.isActive = "0"
      }else{
        this.form.nssJxParents.splice(index,1)
      }
    },
    jxParentsValid(){
      let regMobile = /^[1][2,3,4,5,6,7,8,9][0-9]{9}$/
      let res = true
      let nssJxParents = new Array();
      for(let i of this.form.nssJxParents){
        nssJxParents.push(i)
      }
      if(nssJxParents && nssJxParents.length>0){
        for(let [index, i] of nssJxParents.entries()){
          if(!i.relation){
            i.valid = "0"
            i.error = "请选择关系"
            res = false
          }else if(!i.mobile){
            i.valid = "0"
            i.error = "请输入家长手机"
            res = false
          }else if(!regMobile.test(i.mobile)){
            i.valid = "0"
            i.error = "请输入正确手机号"
            res = false
          }else{
            for(let [cindex, j] of nssJxParents.entries()){
              if(index != cindex && i.mobile == j.mobile){
                j.error = "手机号重复，请更正"
                i.error = "手机号重复，请更正"
                j.valid = "0"
                i.valid = "0"
                res = false
              }
            }
            if(res){
              i.valid = "1"
            }
          }
        }
      }
      this.form.nssJxParents = nssJxParents
      return res
    },
    handleArchives(item){
      this.$router.push("/JX/jxstudent/archives/"+item.studentCod)
    }
  }
};
</script>
<style scope>
  .tree-side{
    height: 700px;
    overflow: auto;
  }
  .parent-item{
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 22px;
    border: 1px solid rgb(220, 223, 230);
    border-radius: 4px;
    position: relative;
  }
  .parent-item.invalid{
    border-color: #ff4949
  }
  .parent-item .valid-error{
    color: #ff4949;
    font-size: 12px;
    line-height: 1;
    padding-top: 4px;
    position: absolute;
    top: 100%;
    left: 0;
  }
  .parent-item .el-input .el-input__inner {
    border: none;
  }
</style>
